<template>
  <el-container class="template-layout">
    <!-- 顶部查询 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
        :searchOptions="searchOptions"
        :loading="loading"
        @getSearchData="getSearchData"
        @resetFields="resetFields"
      />
    </el-header>

    <el-main>
      <!-- 工具栏与右侧操作：表格尺寸/显示查询/列设置 -->
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="addItem">{{
            $t("common.add")
          }}</el-button>
          <el-button type="danger" @click="delItems" plain>{{
            $t("common.delete")
          }}</el-button>
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{
                  $t("table.mini")
                }}</el-dropdown-item>
                <el-dropdown-item command="small">{{
                  $t("table.small")
                }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{
                  $t("table.medium")
                }}</el-dropdown-item>
                <el-dropdown-item command="large">{{
                  $t("table.large")
                }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            :icon="'Search'"
            circle
            @click="showSearchHeader = !showSearchHeader"
          />
          <el-button
            :icon="'Operation'"
            circle
            @click="showColumnSetting = true"
          />
        </template>
      </zz-PageBar>

      <!-- 表格 -->
      <zz-Table
        ref="tableRef"
        :key="tableKey"
        :data="tableData"
        :size="tabelSize"
        :loading="loading"
        :page="tablePage"
        :hasPage="true"
        @pageChange="pageChange"
      >
        <vxe-column type="checkbox" fixed="left" width="40" />
        <vxe-column type="seq" fixed="left" width="50" />

        <!-- 动态列渲染：根据 tableColumns -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :width="column.width || 150"
          >
            <template #default="{ row }">
              <div v-if="editingRow === row">
                <template v-if="column.field === 'tableName'">
                  <el-select
                    v-model="row.tableId"
                    placeholder="请选择"
                    clearable
                    @change="onTableChange(row)"
                  >
                    <el-option
                      v-for="opt in tableOptions"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>
                </template>
                <template v-else-if="column.field === 'version'">
                  <el-input v-model="row.version" size="small" />
                </template>
                <template v-else-if="column.field === 'remark'">
                  <el-input v-model="row.remark" size="small" />
                </template>
                <template v-else>
                  {{ row[column.field] }}
                </template>
              </div>
              <div v-else>
                <template v-if="column.field === 'schemaId'">
                  <a @click="editItem(row)">{{ row[column.field] }}</a>
                </template>
                <template v-else>
                  {{ row[column.field] }}
                </template>
              </div>
            </template>
          </vxe-column>
        </template>

        <!-- 操作列 -->
        <vxe-column
          :title="$t('common.operation')"
          :width="240"
          fixed="right"
          align="center"
        >
          <template v-slot="{ row }">
            <template v-if="editingRow === row">
              <zz-TableBtn
                type="success"
                :loading="btnLoading"
                @click="confirmEdit"
                >{{ $t("common.confirm") }}</zz-TableBtn
              >
              <zz-TableBtn
                type="info"
                :loading="btnLoading"
                @click="cancelEdit"
                >{{ $t("common.cancel") }}</zz-TableBtn
              >
            </template>
            <template v-else>
              <zz-TableBtn
                type="text"
                :loading="btnLoading"
                @click="setEdit(row)"
                >{{ $t("common.edit") }}</zz-TableBtn
              >
              <zz-TableBtn
                type="error"
                :loading="btnLoading"
                @click="delItem(row)"
                >{{ $t("common.delete") }}</zz-TableBtn
              >
            </template>
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>
  </el-container>

  <!-- 列设置：使用本地存储，键名 code-generator_columns -->
  <zz-ColumnSetting
    v-model="showColumnSetting"
    :columns="tableColumns"
    :default-columns="defaultTableColumns"
    storage-key="code-generator_columns"
    list-id="code-generator-column-list"
    drawer-class="code-generator-column-setting-drawer"
    @confirm="handleColumnConfirm"
    @cancel="handleColumnCancel"
    @reset="handleColumnReset"
  />
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from "vue";
const { proxy } = getCurrentInstance();

// UI 状态
const showSearchHeader = ref(true);
const showColumnSetting = ref(false);
const loading = ref(false);
const btnLoading = ref(false);
const editingRow = ref(null);
const backupRow = ref(null);
const tableOptions = ref([]);

// 初始化
const init = () => {
  // todo:
  loadColumnSettings();
  loadTableOptions();
};

// 查询模型与配置
const searchModel = ref({
  schemaId: "",
  tableId: "",
  tableName: "",
  version: "",
  createBy: "",
  createDateRange: [],
  updateBy: "",
  updateDateRange: [],
  remark: "",
});

const searchOptions = computed(() => ({
  model: searchModel,
  column: [
    {
      label: proxy.$t("gen_form_schema_t.schema_id"),
      type: "inputText",
      field: "schemaId",
    },
    {
      label: proxy.$t("gen_form_schema_t.table_name"),
      type: "inputText",
      field: "tableName",
    },
    {
      label: proxy.$t("gen_form_schema_t.version"),
      type: "inputText",
      field: "version",
    },
    {
      label: proxy.$t("gen_form_schema_t.remark"),
      type: "inputText",
      field: "remark",
    },
  ],
}));

// 查询事件
const getSearchData = (val) => {
  searchModel.value = val;
  query("search");
};
// 重置查询表单
const resetFields = () => {
  searchModel.value = {
    schemaId: "",
    tableId: "",
    tableName: "",
    version: "",
    createBy: "",
    updateBy: "",
    remark: "",
  };
};

// 表格与分页
const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const tabelSize = ref("small");
const tableRef = ref(null);

// 处理表格大小变化
const handleSizeChange = (size) => {
  tabelSize.value = size;
};

// 列配置与本地存储键
const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
const tableKey = ref(0);

// 当前列配置与默认列
const tableColumns = ref([
  {
    field: "schemaId",
    title: proxy.$t("gen_form_schema_t.schema_id"),
    visible: true,
    fixed: "left",
    width: 300,
  },
  {
    field: "tableId",
    title: proxy.$t("gen_form_schema_t.table_id"),
    visible: false,
    fixed: null,
    width: 300,
  },
  {
    field: "tableName",
    title: proxy.$t("gen_form_schema_t.table_name"),
    visible: true,
    fixed: null,
  },
  {
    field: "version",
    title: proxy.$t("gen_form_schema_t.version"),
    visible: true,
    fixed: null,
  },
  {
    field: "remark",
    title: proxy.$t("gen_form_schema_t.remark"),
    visible: true,
    fixed: null,
  },
  {
    field: "createBy",
    title: proxy.$t("gen_form_schema_t.create_by"),
    visible: true,
    fixed: null,
  },
  {
    field: "createDate",
    title: proxy.$t("gen_form_schema_t.create_date"),
    visible: true,
    fixed: null,
  },
  {
    field: "updateBy",
    title: proxy.$t("gen_form_schema_t.update_by"),
    visible: true,
    fixed: null,
  },
  {
    field: "updateDate",
    title: proxy.$t("gen_form_schema_t.update_date"),
    visible: true,
    fixed: null,
  },
]);
const defaultTableColumns = ref([
  {
    field: "schemaId",
    title: proxy.$t("gen_form_schema_t.schema_id"),
    visible: true,
    fixed: "left",
    width: 300,
  },
  {
    field: "tableId",
    title: proxy.$t("gen_form_schema_t.table_id"),
    visible: false,
    fixed: null,
    width: 300,
  },
  {
    field: "tableName",
    title: proxy.$t("gen_form_schema_t.table_name"),
    visible: true,
    fixed: null,
  },
  {
    field: "version",
    title: proxy.$t("gen_form_schema_t.version"),
    visible: true,
    fixed: null,
  },
  {
    field: "remark",
    title: proxy.$t("gen_form_schema_t.remark"),
    visible: true,
    fixed: null,
  },
  {
    field: "createBy",
    title: proxy.$t("gen_form_schema_t.create_by"),
    visible: true,
    fixed: null,
  },
  {
    field: "createDate",
    title: proxy.$t("gen_form_schema_t.create_date"),
    visible: true,
    fixed: null,
  },
  {
    field: "updateBy",
    title: proxy.$t("gen_form_schema_t.update_by"),
    visible: true,
    fixed: null,
  },
  {
    field: "updateDate",
    title: proxy.$t("gen_form_schema_t.update_date"),
    visible: true,
    fixed: null,
  },
]);

// 处理列设置确认
const handleColumnConfirm = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
  all["code-generator_columns"] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};
// 处理列设置取消
const handleColumnCancel = () => {
  loadColumnSettings();
};
// 处理列设置重置
const handleColumnReset = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
  all["code-generator_columns"] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};

// 加载已保存列设置
const loadColumnSettings = () => {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY))?.[
      "code-generator_columns"
    ];
    if (saved) tableColumns.value = saved;
    tableKey.value += 1;
  } catch (e) {
    console.error(proxy.$t("table.loadColumnSettingsFailed"), e);
  }
};

// 查询
const query = async (mode) => {
  loading.value = true;
  if (mode === "search") {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    };
  }
  // TODO: 接入测试管理查询接口，替换为真实 API
  let params = dealParams();
  let res = await proxy.$API.codeManagement.formSchema.queryWithPage.post(
    params
  );
  if (res.code === "01") {
    tableData.value = res.bizList;
    tablePage.value.total = res.total;
    tablePage.value.pageSize = res.pageSize;
  }
  loading.value = false;
};
// 处理查询参数
const dealParams = () => {
  let params = {
    ...searchModel.value,
  };

  // 其他的参数转化逻辑，如日期格式等
  return params;
};

// 业务操作占位
const addCodeGeneratorRef = ref(null);
const addCodeGeneratorIsOpen = ref(false);
const addItem = () => {
  proxy.$router.push({ name: "FormDesigner" });
};
const delItems = async () => {
  const rows = tableRef.value?.getCheckboxRecords?.() || [];
  if (rows.length === 0)
    return proxy.$message.warning(proxy.$t("message.selectItemsToDelete"));
  let ids = rows.map((e) => e.schemaId);
  proxy
    .$confirm(
      proxy.$t("message.confirmDelete"),
      proxy.$t("message.deleteConfirm"),
      {
        confirmButtonText: proxy.$t("common.confirm"),
        cancelButtonText: proxy.$t("common.cancel"),
        type: "warning",
      }
    )
    .then(async () => {
      let res = await proxy.$API.codeManagement.formSchema.deleteBatch.post(
        ids
      );
      if (res.code === "01") {
        query("search");
        proxy.$message.success(proxy.$t("message.deleteSuccess"));
      } else {
        proxy.$message.error(res.msg || proxy.$t("message.deleteFailed"));
      }
    })
    .catch((e) => {
      console.error(proxy.$t("message.deleteFailed"), e);
      proxy.$message.info(proxy.$t("message.deleteCanceled"));
    });
};
const delItem = async (row) => {
  let id = row.schemaId;
  proxy
    .$confirm(
      proxy.$t("message.confirmDelete"),
      proxy.$t("message.deleteConfirm"),
      {
        confirmButtonText: proxy.$t("common.confirm"),
        cancelButtonText: proxy.$t("common.cancel"),
        type: "warning",
      }
    )
    .then(async () => {
      let res = await proxy.$API.codeManagement.formSchema.delete.get(id);
      if (res.code === "01") {
        query("search");
        proxy.$message.success(proxy.$t("message.deleteSuccess"));
      } else {
        proxy.$message.error(res.msg || proxy.$t("message.deleteFailed"));
      }
    })
    .catch(() => {
      proxy.$message.info(proxy.$t("message.deleteCanceled"));
    });
};
const viewItem = (row) => {
  proxy.$router.push({
    name: "FormDesigner",
    query: { schemaId: row.schemaId },
  });
};
const editItem = (row) => {
  proxy.$router.push({
    name: "FormDesigner",
    query: { schemaId: row.schemaId },
  });
};

const setEdit = (row) => {
  editingRow.value = row;
  backupRow.value = JSON.parse(JSON.stringify(row));
};

const cancelEdit = () => {
  if (editingRow.value && backupRow.value) {
    Object.assign(editingRow.value, backupRow.value);
  }
  editingRow.value = null;
  backupRow.value = null;
};

const confirmEdit = async () => {
  if (!editingRow.value) return;
  try {
    const payload = {
      schemaId: editingRow.value.schemaId,
      tableId: editingRow.value.tableId ?? "",
      tableName: editingRow.value.tableName ?? "",
      version: editingRow.value.version,
      remark: editingRow.value.remark,
    };
    let res = await proxy.$API.codeManagement.formSchema.modify.post(payload);
    if (res.code === "01") {
      proxy.$message.success("更新成功");
      editingRow.value = null;
      backupRow.value = null;
      query();
    } else {
      proxy.$message.error(res.msg || "更新失败");
    }
  } catch (e) {
    proxy.$message.error("更新失败");
  }
};

const onTableChange = (row) => {
  const id = row.tableId;
  if (!id) {
    row.tableId = "";
    row.tableName = "";
    return;
  }
  const opt = tableOptions.value.find((o) => o.value === id);
  if (opt) {
    row.tableName = opt.name || opt.label;
  } else {
    row.tableName = "";
  }
};

const loadTableOptions = async () => {
  try {
    const system = "zz-admin";
    const res = await proxy.$API.codeManagement.codeGen.queryAll.get(system);
    if (res.code === "01") {
      tableOptions.value = (res.data || []).map((e) => ({
        value: e.tableId,
        label: e.tableName,
        name: e.tableName,
      }));
    }
  } catch (e) {
    console.error("加载业务表选项失败", e);
  }
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage;
  searchModel.value.queryParam.pageSize = page.pageSize;
  query();
};

onMounted(() => {
  init();
  query("search");
});
</script>

<style lang="less" scoped></style>
